﻿using api.Plugins;
using DataProvider;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Utility;

namespace api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class Sys_UserController : ControllerBase
    {
        private readonly IConfiguration _configuration = null;
        private readonly Sys_UserProvider _userProvider= Sys_UserProvider.Instances;
        public Sys_UserController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public class UserLoginModel
        {
            public string userName { get; set; }
            public string passWord { get; set; }
        }
        [SkipActionFilter]
        [HttpPost]
        [AllowAnonymous]
        public IActionResult SysLogin(UserLoginModel param)
        {
            if (string.IsNullOrEmpty(param.userName) || string.IsNullOrEmpty(param.passWord))
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1, data = "param error，please refresh the broswer" }));
            }

            var userEnt = Sys_UserProvider.Instances.GetEntity(param.userName);
            if(userEnt==null)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1, data = "no this account,please confirm" }));
            }
            if (userEnt.UserStatus != UserStatus.normal)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1, data = "login forbidden" }));
            }
            if(userEnt.PassWord!=param.passWord)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1, data = "password error" }));
            }

            double expireMinute = 10080;//七天
            double.TryParse(_configuration["AppSettings:JwtBearer:ExpireMinute"].ToString(), out expireMinute);
            //登录成功
            var jwtToken = JwtHelp.SetToken(_configuration, userEnt.UserName);
            //缓存key
            var cacheKey = $"{_configuration["AppSettings:JwtBearer:TokenHeader"]} {jwtToken}";
            DateTime expireTime = DateTime.Now.AddMinutes(expireMinute);
            
            List<int> UserIds = new List<int>();
            
            UserCache userCache = new UserCache()
            {
                IsSuperAdmin = userEnt.IsSuperAdmin == 1 ? true : false,
                UserId = userEnt.Id,
                DeptId = userEnt.DeptId,
                UserName = userEnt.UserName,
                RealName = userEnt.RealName,
                EnglishName = userEnt.EnglishName,
                UserToken = cacheKey,
                ExpireTime = expireTime,
                
                Email = userEnt.Email,
                UserRoleIds = UserIds
               
            };
            RedisBase.Item_Set(cacheKey, userCache);
            //RedisBase.Item_Set(cacheKey, userCache, 1);
            RedisBase.Item_SetExpire(cacheKey, expireTime);
            //RedisBase.Item_SetExpire(cacheKey, expireTime, 1);
            //登录日志写入文件
            //var loginInfoPath = Environment.CurrentDirectory + "/Config/LoginInfo.json";
            return Ok(JsonConvert.SerializeObject(new ResultData<object>(userCache)));
        }

        [HttpPost]
        public IActionResult GetList(UserQuery param)
        {
            var res = _userProvider.GetList(param, out int total);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>
            {
                data = res,
                count = total
            }));
        }
        [HttpPost]
        public IActionResult SaveForm(Sys_User param)
        {
            if (param == null || string.IsNullOrEmpty(param.UserName) || string.IsNullOrEmpty(param.RealName))
                return Ok(ResultData.TipMsg("Param Error！"));

            var user = this.GetUserToken();
            var res = _userProvider.SaveModel(user.UserId, param,out string errMsg);
            return Ok(res>0?ResultData.Success("Save Success！"):ResultData.TipMsg(errMsg));
        }
        [HttpPost]
        public IActionResult Delete(int[] ids)
        {
            if (ids == null || ids.Length == 0)
                return Ok(ResultData.TipMsg("Param Error！"));

            var userToken = this.GetUserToken();
            var res = _userProvider.Del(userToken.UserId,ids);
            return Ok(res > 0 ? ResultData.Success("Del Success！") : ResultData.TipMsg("DelFail！"));
        }
    }
}
